/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package listcontrol;

import controllers.DatabaseController;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import util.File;
import static java.nio.file.StandardWatchEventKinds.*;
import java.nio.file.WatchEvent;
import util.CompleteFile;

/**
 *
 * @author gravena
 */
public class WatchThread implements Runnable {

    private final DatabaseController dbController;
    private WatchService watcher;
    private WatchKey key;

    public WatchThread(DatabaseController dbController) {
        //SE POSSÍVEL, USAR APENAS OS MÉTODOS DO DBCONTROLLER, SEM ACESSAR LOCAL LIST
        this.dbController = dbController;
        Path dir = Paths.get(File.sharePath);
        try {
            watcher = FileSystems.getDefault().newWatchService();
            key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        } catch (IOException ex) {
            System.err.println("Erro ao adicionar o watcher da pasta compartilhada.");
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                WatchKey eventKey;
                key = this.watcher.take();

                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path filename = ev.context();
                    if (kind == ENTRY_CREATE) {
                        synchronized (this.dbController) {
                            if (this.dbController.addCompleteFile(new CompleteFile(filename.toString()))) {
                                this.dbController.incLocalVersion();
                            }
                        }
                    } else if (kind == ENTRY_DELETE) {
                        synchronized (this.dbController) {
                            if (this.dbController.removeCompleteFile(filename.toString())) {
                                this.dbController.incLocalVersion();
                            } else {
                                System.err.println("Não foi possível encontrar " + filename);
                            }
                        }
                    } else if (kind == ENTRY_MODIFY) {
//                        synchronized (this.dbController) {
//                            dbController.rebuildLocalList();
//                            this.dbController.incLocalVersion();
//                        }
                    }
                }
                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            } catch (InterruptedException | IOException ex) {
                System.err.println("Erro no tratamento de eventos do sistema de arquivo");
            }
        }
    }
}
